package czk.concrent.enjoyModelWithNotLock.unsafe.practice;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/9/6 21:56
 */
public class UnsafePractice {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InterruptedException {
        // 反射获取unsafe类
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        // 设置为可访问
        field.setAccessible(true);
        // 获取unsafe对象
        Unsafe unsafe = (Unsafe) field.get(null);
        // 获取unsafe的类加载器对象
        System.out.println(unsafe.getClass().getClassLoader());
        // 创建对象
        Student student=new Student("czk",26);
        // 获取偏移地址
        long name = unsafe.objectFieldOffset(Student.class.getDeclaredField("name"));
        System.out.println(name);
        long age = unsafe.objectFieldOffset(Student.class.getDeclaredField("age"));
        System.out.println(age);
        // 重新设置变量
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                unsafe.compareAndSwapObject(student,name,"czk","czj");
                unsafe.compareAndSwapInt(student,age,26,28);
            }).start();
        }
        Thread.sleep(2*1000);
        // 打印
        System.out.println(student);
    }
}
class Student{
    private volatile   String name;
    private volatile   int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
